# @Time : 2024/7/28 13:19
# @Author : Adam
# @Version : v1.0
# @IDE : PyCharm
# @Project : tracer
import json
import os
from django.shortcuts import render
from web.forms.file import FolderModelForm
from django.http import JsonResponse
from web import models
from django.forms import model_to_dict
from django.views.decorators.csrf import csrf_exempt


# http://127.0.0.1:8000/manage/9/file
# http://127.0.0.1:8000/manage/9/file/?folder=9
def file(request, project_id):
    """文件列表 & 添加文件夹"""

    parent_object = None
    folder_id = request.GET.get('folder', "")
    if folder_id.isdecimal():
        parent_object = models.FileRepository.objects.filter(id=folder_id, file_type=2,
                                                             project=project_id).first()

    if request.method == 'GET':

        breadcrumb_list = []
        parent = parent_object
        while parent:
            # breadcrumb_list.insert(0, {'id': parent.id, 'name': parent.name})
            breadcrumb_list.insert(0, model_to_dict(parent, ['id', 'name']))
            parent = parent.parent

        # 当前目录下所有的文件 & 文件夹获取到即可
        queryset = models.FileRepository.objects.filter(project_id=project_id)
        if parent_object:
            # 进入某目录
            file_object_list = queryset.filter(parent=parent_object).order_by('-file_type')
        else:
            # 根目录
            file_object_list = queryset.filter(parent__isnull=True).order_by('-file_type')

        form = FolderModelForm(request, parent_object)
        context = {
            'form': form,
            'file_object_list': file_object_list,
            'breadcrumb_list': breadcrumb_list

        }
        return render(request, 'file.html', context)

    # POST 添加文件夹 & 文件夹修改
    fid = request.POST.get('fid', '')

    edit_object = None
    if fid.isdecimal():
        # 修改
        edit_object = models.FileRepository.objects.filter(id=fid, file_type=2, project_id=project_id).first()

    if edit_object:
        form = FolderModelForm(request, parent_object, data=request.POST, instance=edit_object)
    else:
        # 添加
        form = FolderModelForm(request, parent_object, data=request.POST)

    if form.is_valid():
        form.instance.project = request.tracer.project
        form.instance.file_type = 2
        form.instance.update_user = request.tracer.user
        form.instance.parent = parent_object
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# http://127.0.0.1:8000/manage/9/file/delete/?fid=1
def file_delete(request, project_id):
    """删除文件"""
    fid = request.GET.get('fid')

    # 删除数据库中的文件&文件夹（级联删除）
    delete_object = models.FileRepository.objects.filter(id=fid, project_id=project_id).first()
    if delete_object.file_type == 1:
        pass
        # 删除文件，将容量还给项目当前已使用空间
        request.tracer.project.use_space -= delete_object.file_size
        request.tracer.project.save()

        # 在数据库中删除当前文件
        delete_object.delete()
        return JsonResponse({'status': True})

    # 删除文件夹 找他下面的文件和文件夹
    # models.FileRepository.objects.filter(parent=delete_object)  # 文件 删除; 文件夹 继续向里查

    total_size = 0
    folder_list = [delete_object]
    for folder in folder_list:
        child_list = models.FileRepository.objects.filter(project_id=project_id, parent=folder).order_by('-file_type')
        for child in child_list:
            if child.file_type == 2:
                folder_list.append(child)
            else:
                total_size += child.file_size
    # 归还容量
    if total_size:
        request.tracer.project.use_space -= total_size
        request.tracer.project.save()
    # 删数据库中的文件
    delete_object.delete()
    return JsonResponse({'status': True})


@csrf_exempt
def file_upload(request, project_id):
    files = request.FILES.getlist('files')
    upload_path = 'media/upload/'
    if not os.path.exists(upload_path):
        os.makedirs(upload_path)
    # 获取价格策略里单文件最大值
    per_file_limit = request.tracer.price_policy.per_file_size * 1024 * 1024
    total_file_limit = request.tracer.price_policy.project_space * 1024 * 1024 * 1024

    total_size = 0

    for f in files:
        if f.size > per_file_limit:
            msg = f'单文件超出最大限制（{request.tracer.price_policy.per_file_size}M），文件：{f.name}，请升级套餐。'
            return JsonResponse({'status': False, 'error': msg})
        total_size += f.size

    # 总容量进行限制
    # 项目的允许的空间 request.tracer.price_policy.project_space
    # 已使用的空间 request.tracer.project.use_space
    if request.tracer.project.use_space + total_size > total_file_limit :
        return JsonResponse({'status': False, 'error': '容量超过限制，请升级套餐'})
    return JsonResponse({'status': True})

# for f in files:
#     print(f.size)
#     file_name = f.name
#     with open(f'media/upload/{file_name}', 'wb') as destination:
#         for chunk in f.chunks():
#             destination.write(chunk)
# 获取价格策略里单文件最大值
# per_file_limit = request.tracer.price_policy.per_file_size * 1024 * 1024
#
# total_size = 0
# file_list = json.loads(request.body.decode('utf-8'))
#
# for item in file_list:
#     print(item['size'])
#     # 单文件的字节大小 item['size']=B
#     # 单文件限制的大小 M
#     # 超出限制
#     # print(item)
#     # print(request.FILES['file'])
#     if item['size'] > per_file_limit:
#         msg = f'单文件超出最大限制（{request.tracer.price_policy.per_file_size}M），文件：{item['name']}，请升级套餐。'
#         return JsonResponse({'status': False, 'error': msg})
#     total_size += item['size']
#
# # 总容量进行限制
# # 项目的允许的空间 request.tracer.price_policy.project_space
# # 已使用的空间 request.tracer.project.use_space
# if request.tracer.project.use_space + total_size > request.tracer.price_policy.project_space * 1024 * 1024:
#     return JsonResponse({'status': False, 'error': '容量超过限制，请升级套餐'})
# return JsonResponse({'status': True})
